package com.sharding.jdbc.demo2.service.impl;

import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sharding.jdbc.demo.util.UserUtils;
import com.sharding.jdbc.demo2.mapper.PvMapper;
import com.sharding.jdbc.demo2.mapper.UserMapper;
import com.sharding.jdbc.demo2.model.Pv;
import com.sharding.jdbc.demo2.model.User;
import com.sharding.jdbc.demo2.service.UserService;
import com.sharding.jdbc.demo2.util.ShardingUtils;
import lombok.extern.slf4j.Slf4j;

/**
* @comments
* @author  zg
* @date 2021年1月1日
*/
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PvMapper pvMapper;
    
    @Override
    public void createUsers(int userCount) {
        for (int i = 0; i < userCount; i++) {
            String name = UserUtils.getName();//随机出一个姓名
            int age = UserUtils.getAge();//随机出年龄
            User user = User.builder().name(name).age(age).build();
            int count = userMapper.insert(user);
            if(count > 0) {
                int uid = user.getId();
                log.info("创建用户uid={}", uid);
                //得出分表的表名，如果表不存在，则创建
                String shardingTable = ShardingUtils.getShardingTableByRange("pv", ShardingUtils.pv_segmentSize, uid);
                if(pvMapper.isTableExist(shardingTable) == 0) {
                    log.info("用户id为{}, 用户pv分表{}不存在，则创建...", uid, shardingTable);
                    pvMapper.createTable(shardingTable);
                }
            }
        }
        
    }

    @Override
    public void randomUserVisit(int maxUserCount, int visitTimes) {
        
        List<User> userList = userMapper.selectUserList(maxUserCount);
        int userListSize = userList.size();
        
        Random random = new Random();
        for (int i = 0; i < visitTimes; i++) {
            //随机选取一个用户
            User randomUser = userList.get(random.nextInt(userListSize));
            //保存用户访问记录
            Pv pv = Pv.builder().uid(randomUser.getId()).uri("/path/12345").build();
            pvMapper.insert(pv);
        }
        
    }

}
